<template>
  <el-card shadow="hover" class="border-0">
    <list-header @refresh="getData" @create="handleCreate" />

    <el-tree :data="tableData" :props="{ children: 'child', label: 'name' }" v-loading="loading" node-key="id"
      :default-expanded-keys="defaultExpandedKeys">
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <el-tag size="small" :type="data.menu ? '' : 'info'">
            {{ data.menu ? '菜单' : '权限' }}
          </el-tag>
          <el-icon v-if="data.icon" :size="16" class="ml-2">
            <component :is="data.icon"></component>
          </el-icon>
          <span>{{ data.name }}</span>

          <div class="ml-auto" @click.stop="() => {}">
            <el-switch :modelValue="data.status" :active-value="1" :inactive-value="0" @change="handleStatusChange($event, data)"/>

            <el-button type="primary" size="small" @click.stop="handleEdit(data)" text>
              修改
            </el-button>
            <el-button type="primary" size="small" @click.stop="addChild(data.id)" class="mr-[12px]" text>
              增加
            </el-button>

            <span @click.stop="() => {}">
              <el-popconfirm title="是否要删除该记录？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDelete(data.id)">
                <template #reference>
                  <el-button text type="primary" size="small"> 删除 </el-button>
                </template>
              </el-popconfirm>
            </span>
          </div>
        </div>
      </template>
    </el-tree>

    <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSumbit" @cancel="handleCancel">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="120px" :inline="false">
        <el-form-item label="上级菜单" prop="rule_id">
          <!-- 
            checkStrictly = true 来设置父子节点取消选中关联，从而达到选择任意一级选项的目的。 
            emitPath = false, 返回该节点的值
          -->
          <el-cascader v-model="form.rule_id" :options="ruleList" 
            :props="{ value: 'id',label: 'name',children: 'child', checkStrictly: true,emitPath: false }"
            placeholder="请选择上级菜单"
          />
        </el-form-item>

        <el-form-item label="菜单/规则" prop="menu">
          <el-radio-group v-model="form.menu">
            <el-radio :label="1" size="default" border>菜单</el-radio>
            <el-radio :label="0" size="default" border>规则</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" style="width: 30%"/>
        </el-form-item>

        <el-form-item label="菜单图标" prop="icon" v-if="form.menu === 1">
          <icon-select v-model="form.icon" style="width: 200px;"/>
        </el-form-item>

        <el-form-item label="前端路由" prop="frontpath" v-if="form.menu === 1 && form.rule_id > 0">
          <el-input v-model="form.frontpath" placeholder="请输入前端路由" />
        </el-form-item>

        <el-form-item label="后端规则" prop="condition" v-if="form.menu === 0">
          <el-input v-model="form.condition" placeholder="请输入后端规则" />
        </el-form-item>

        <el-form-item label="请求方式" prop="method" v-if="form.menu === 0">
          <el-select v-model="form.method" placeholder="请选择">
            <el-option v-for="item in ['GET', 'POST', 'PUT', 'DELETE']" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="order">
          <el-input-number v-model="form.order" :min="0" :max="100" />
        </el-form-item>
      </el-form>
    </FormDrawer>
  </el-card>
</template>

<script setup>
  import { ref } from 'vue'
  import ListHeader from '@/components/ListHeader.vue'
  import FormDrawer from '@/components/FormDrawer.vue'
  import IconSelect from '@/components/IconSelect.vue'
  import {
    getRuleListApi,
    createRuleApi,
    updateRuleApi,
    updateRuleStatusApi,
    deleteRuleApi,
  } from '@/api/rule.js'
  import { useInitTable, useInitForm } from '@/hooks/useCommon.js'

  const defaultExpandedKeys = ref([])
  const ruleList = ref([])
  const {
    tableData,
    loading,
    currentPage,
    total,
    limit,
    getData,
    handleDelete,
    handleStatusChange,
  } = useInitTable({
    getlist: getRuleListApi,
    delete: deleteRuleApi,
    updateStatus: updateRuleStatusApi,
    onGetListSuccess: (res) => {
      tableData.value = res.list.map((o) => {
        o.statusLoading = false
        return o
      })
      ruleList.value = res.rules
      defaultExpandedKeys.value = res.list.map((item) => item.id)
    },
  })

  const {
    formRef,
    formDrawerRef,
    form,
    rules,
    drawerTitle,
    editId,
    handleCreate,
    handleEdit,
    handleSumbit,
    handleCancel,
  } = useInitForm({
    form: {
      rule_id: 0,
      menu: 0,
      name: '',
      condition: '',
      method: 'GET',
      status: 1,
      order: 50,
      icon: '',
      frontpath: '',
    },
    rules: {},
    getData,
    create: createRuleApi,
    update: updateRuleApi,
  })

  // 增加子菜单
  function addChild(id) {
    handleCreate()
    form.rule_id = id
    form.status = 1
  }
</script>

<style scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
    padding-right: 8px;
  }
  :deep(.el-tree-node__content) {
    padding: 20px 0 !important;
  }
  /* tree 子元素 */
  :deep(.el-tree-node__children) {
    padding-left: 20px;
  }
  .el-tag {
    margin-right: 5px;
  }
</style>
